<?php
namespace app\manage\controller;
use think\Db;

class OrderDetail extends Base
{
    public function index(){
        if(request()->isAjax() || input('?export')){
            $page = input('page');
            $limit = input('limit');
            $date = explodeTime(input('date'));
            $myUserId = input('my_user_id');
            $roleId = input('role_id');
            $serverId = input('server_id');
            $myOrderId = input('my_order_id');
            $chOrderId = input('ch_order_id');
            $payOrderId = input('pay_order_id');
            $debug = input('debug');
            $gameId = input('game_id');
            $channelId = input('channel_id');
            $gameResult = input('game_result');
            $payResult = input('pay_result');

            $where = '1';
            $where .= " && order_time between '{$date['start_time']}' AND '{$date['end_time']}'";
            !empty($myUserId) && $where .= " && (my_user_id='{$myUserId}' OR my_user_name like '%{$myUserId}%')";
            !empty($roleId) && $where .= " && (role_id='{$roleId}' OR role_name like '%{$roleId}%')";
            !empty($serverId) && $where .= " && (server_id='{$serverId}' OR server_name like '%{$serverId}%')";
            !empty($myOrderId) && $where .= " && my_order_id='{$myOrderId}'";
            !empty($chOrderId) && $where .= " && ch_order_id='{$chOrderId}'";
            !empty($payOrderId) && $where .= " && pay_order_id='{$payOrderId}'";
            !empty($gameId) && $where .= " && game_id='{$gameId}'";
            if(!empty($gameResult)){
                if($gameResult == 1){
                    $where .= " && game_result='{$gameResult}'";
                }else{
                    $where .= " && game_result='0'";
                }
            }
            if(!empty($payResult)){
                if($payResult == 1){
                    $where .= " && pay_result='{$payResult}'";
                }else{
                    $where .= " && pay_result='0'";
                }
            }
            if(!empty($debug)){
                if($debug == 1){
                    $where .= " && debug='{$debug}'";
                }else{
                    $where .= " && debug='0'";
                }
            }
            if( !empty($channelId) ){
                if($channelId >= 5000){ //联运
                    $where .= " && channel_id='{$channelId}'";
                }else{ //CPS
                    $allChannelId = model('Channel')->allChannelId($channelId);
                    $where .= " && channel_id='1000' && reg_cps_id in ({$allChannelId})";
                }
            }

            $start = ($page-1)*$limit;
            $length = $limit;

            $y1 = date('Y', $date['start_time']);
            $y2 = date('Y', $date['end_time']);

            $sum = 0;
            if($y1 == $y2){ //同一年
                $count = Db::name('PayOrderY_'.$y1)->where($where)->count();

                $select = Db::name('PayOrderY_'.$y1)
                    ->where($where)
                    ->limit($start, $length)
                    ->order('order_time desc')
                    ->select();

                if(!empty($myUserId) || !empty($roleId) || !empty($serverId)){
                    $sum = Db::name('PayOrderY_'.$y1)
                        ->where($where)
                        ->sum('total_price');
                }
            }else{ //跨年
                $field = "order_time, channel_id, reg_cps_id, game_id, my_user_id, my_user_name, role_id, role_name, server_id, server_name, my_order_id, ch_order_id, pay_order_id, cp_order_id, total_price, product_name, pay_type, pay_time, pay_result, game_result, ratio, coin, debug, rebate_time, notifyed";
                $subQuery = Db::name('PayOrderY_'.$y1)
                    ->field($field)
                    ->where($where)
                    ->union("select {$field} from sdk_pay_order_y_{$y2} where ({$where})", true)
                    ->buildSql();

                $count = Db::table($subQuery.' y')->count();

                $select = Db::table($subQuery.' y')
                    ->limit($start, $length)
                    ->order('order_time desc')
                    ->select();

                if(!empty($myUserId) || !empty($roleId) || !empty($serverId)){
                    $sum = Db::table($subQuery.' y')
                        ->sum('total_price');
                }
            }

            $gameIdName = model('Game')->gameIdName();
            $channelIdName = model('Channel')->channelIdName();
            $gameIdRebate = changeValKey('ViewGameManage', 'game_id', 'rebate_callback');

            $data = [];
            foreach ($select as $k=>$v){
                if($v['rebate_time']){ //已返利
                    $rebateStatus = 1;
                }else if( $gameIdRebate[$v['game_id']] ){ //有返利地址
                    $rebateStatus = 2;
                }else{
                    $rebateStatus = 3;
                }

                if($v['channel_id']==1000){
                    $channelName = isset($channelIdName[ $v['reg_cps_id'] ]) ? $channelIdName[ $v['reg_cps_id'] ] : '';
                }else{
                    $channelName = isset($channelIdName[ $v['channel_id'] ]) ? $channelIdName[ $v['channel_id'] ] : '';
                }

                $data[] = [
                    'order_time' => date('Y-m-d H:i:s', $v['order_time']),
                    'type' => $v['channel_id']==1000 ? 'CPS' : '联运',
                    'reg_cps_id' => $v['channel_id']==1000 ? $v['reg_cps_id'] : $v['channel_id'],
                    'reg_cps_name' => $channelName,
                    'game_id' => $v['game_id'],
                    'game_name' => $gameIdName[ $v['game_id'] ],
                    'my_user_id' => $v['my_user_id'],
                    'my_user_name' => $v['my_user_name'],
                    'role_id' => $v['role_id'],
                    'role_name' => $v['role_name'],
                    'server_id' => $v['server_id'],
                    'server_name' => $v['server_name'],
                    'cp_order_id' => $v['cp_order_id'],
                    'ch_order_id' => $v['ch_order_id'],
                    'my_order_id' => $v['my_order_id'],
                    'pay_order_id' => $v['pay_order_id'],
                    'total_price' => '¥ ' . $v['total_price']/100,
                    'product_name' => $v['product_name'],
                    'pay_type' => substr($v['pay_type'], 0, 5)=='wxpay' ? '微信' : '支付宝',
                    'pay_time' => $v['pay_time'] ? date('Y-m-d H:i:s', $v['pay_time']) : '',
                    'pay_result' => $v['pay_result'] ? '到账' : '',
                    'game_result' => $v['game_result'] ? '到账' : '',
                    'ratio' => '1' . '：' . $v['ratio'],
                    'coin' => $v['coin'],
                    'debug' => $v['debug'] ? '测试' : '',
                    'rebate_status' => $rebateStatus,
                    'rebate_time' => $v['rebate_time'] ? date('Y-m-d H:i:s', $v['rebate_time']) : '',
                    'notifyed' => $v['notifyed'],
                ];
            }

            $this->layTable(0, '支付订单', $data, $count, round($sum/100, 2));
        }else{
            $date = date('Y-m-d', time()).' - '.date('Y-m-d', time());
            return view('', ['date'=>$date]);
        }
    }

    public function rebate(){
        $myOrderId = input('my_order_id');
        $table = get_order_table($myOrderId);

        if( Db::name($table)->where('my_order_id', $myOrderId)->value('rebate_time') ){
            $this->layJson(1, '修改失败，该订单已修改返利状态');
        }

        if( Db::name($table)->where('my_order_id', $myOrderId)->update(['rebate_time'=>time()]) ){
            $this->layJson(0, '修改成功');
        }else{
            $this->layJson(1, '修改失败，请重试');
        }
    }

    public function oneRebate(){
        $myOrderId = input('my_order_id');

        $myOrderIdArr = explode(',', $myOrderId);

        $gameIdRebate = changeValKey('ViewGameManage', 'game_id', 'rebate_callback');

        $myOrderIdBack = [];
        foreach ($myOrderIdArr as $k=>$v){
            $table = get_order_table($v);
            $order = Db::name($table)->field('game_id, rebate_time')->where('my_order_id', $v)->find();

            if( $order['rebate_time'] ){ //有返利时间
                continue;
            }else if( $gameIdRebate[ $order['game_id'] ] ){ //有返利地址
                continue;
            }

            $myOrderIdBack[] = $v;
            Db::name($table)->where('my_order_id', $v)->update(['rebate_time'=>time()]);
        }
        if($myOrderIdBack){
            $this->layJson(0, '一键返利成功', $myOrderIdBack);
        }else{
            $this->layJson(1, '一键返利失败，请刷新重试');
        }

    }

    public function log(){
        $myOrderId = input('my_order_id'); //米娱订单号

        //查找通知
        $table = get_notify_table($myOrderId);
        $select = Db::name($table)
            ->where(['my_order_id'=>$myOrderId])
            ->select();

        $gameIdName = model('Game')->gameIdName();
        $channelIdName = model('Channel')->channelIdName();

        $order = [];
        foreach($select as $k=>$v){
            $order[] = [
                'id' => $v['id'],
                'url' => $v['url'],
                'input' => $v['input'],
                'output' => $v['output'],
                'time' => date('Y-m-d H:i:s', $v['time']),
                'type' => $v['type'],
                'game_id' => $v['game_id'] . '：' . $gameIdName[ $v['game_id'] ],
                'channel_id' => $v['channel_id'] . '：' . $channelIdName[ $v['channel_id'] ],
                'my_order_id' => $v['my_order_id'],
                'result' => $v['result'],
                'msg' => $v['msg'],
            ];
        }
        return view('', ['order'=>$order]);
    }

    public function againSend(){
        $myOrderId = input('my_order_id'); //米娱订单号

        //查找订单
        $table = get_order_table($myOrderId);
        $order = Db::name($table)->where(['my_order_id'=>$myOrderId])->find();

        //验证订单
        if(!$order){
            $this->layJson(1, '订单未找到');
        }else if($order['game_result']==1){
            $this->layJson(1, '已经发过了,请不要重复发送');
        }

        //查找游戏secret和pay_callback
        $game = Db::name('Game')->where(['game_id'=>$order['game_id']])->find();
        if(empty($game['secret']) || empty($game['pay_callback'])){
            $this->layJson(1, '支付回调参数错误');
        }

        //H5游戏重发
        if( $order['device_type'] == 'H5'){
            if($game['game_id']>1443){
                $cpParams = array(
                    'game_id'   =>$order['game_id'],
                    'my_order_id'        => $order['my_order_id'],
                    'my_user_id'        => $order['my_user_id'],
                    'role_id'        => $order['role_id'],
                    'server_id'     =>$order['server_id'],
                    'total_price'         => $order['total_price'],//分
                    'game_coin'      => $order['coin'],
                    'cp_order_id'      => $order['cp_order_id'],
                    'pay_time'        => $order['pay_time'],
                    'notify_time'      =>time(),
                    'ext'=>$order['ext']
                );
                ksort($cpParams);
                $string = '';
                foreach($cpParams as $key=>$value){
                    $string .= $key . "=" . $value . "&";
                }
                $string = substr($string, 0, -1);
                $string.=':'.$game['secret'];
                $signature =  md5($string);
                $cpParams['sign'] = $signature;
                $result = http($game['pay_callback'], $cpParams, 'POST');
            }else{
                $cpParams = [
                    'game_key' => $order['game_id'],
                    'order_id' => $order['my_order_id'],
                    'user_id' => $order['my_user_id'],
                    'role_id' => $order['role_id'],
                    'amount' => $order['total_price']/100,
                    'game_coin' => $order['coin'],
                    'cp_order_id' => $order['cp_order_id'],
                    'success' => 1,
                ];
                $cpParams['sign'] = $this->createSign($cpParams, 'game_secret', $game['secret']);
                $cpParams['extra'] = $order['ext'];
                $result = http($game['pay_callback'], $cpParams, 'POST');
            }

            //AND/IOS游戏重发
        }else{
            if(($order['game_id']==1257||$order['game_id']==1266||$order['game_id']==1278)&&$order['my_user_id']<=45000000){
                $rs=Db::name('User')->where(['my_user_id'=>$order['my_user_id'],'channel_id'=>$order['channel_id']])->find();
                $order['my_user_id']=$rs['sdkdrive_id'];
            }

            $sdkVersion=$game['sdk_version'];

            if($order['client_id']==107&&$order['game_id']==1176){
                $sdkVersion='v2.0';
            }
            if($sdkVersion=='v1.0'){
                $cpParams = [
                    'order_id'       => $order['my_order_id'],
                    'user_id'        => $order['my_user_id'],
                    'role_id'        => $order['role_id'],
                    'amount'         => $order['total_price']/100,
                    'game_coin'      => (int)$order['coin'],
                    'cp_order_id'    => $order['cp_order_id'],
                    'success'        => 1,
                ];
                ksort($cpParams);
                $string = '';
                foreach($cpParams as $key=>$value){
                    $string .= $key . "=" . $value . "&";
                }
                $signString = substr($string, 0, -1);
                $signString .= ":{$game['secret']}";
                $signature =  md5($signString);
                $cpParams['sign'] = $signature;
                if($order['game_id']==1149){
                    $cpParams['ext'] = str_replace("=","|",$order['ext']);
                }else{
                    $cpParams['ext'] = $order['ext'];
                }
                if($order['game_id']==1152){//银河战姬的充值回调放在扩展参数里--------------------------------------------------------------
                    $ext=json_decode($order['ext'],true);
                    $serverId=$ext['sid'];
                    switch($serverId){
                        case '1501':
                            $game_data['callback']='http://gundacn.sudogame.com/charge/miyucallback';
                            break;
                        case '1502':
                            $game_data['callback']='http://gundacn2.sudogame.com/charge/miyucallback';
                            break;
                        case '1503':
                            $game_data['callback']='http://gundacn3.sudogame.com/charge/miyucallback';
                            break;
                        case '1504':
                            $game_data['callback']='http://gundacn4.sudogame.com/charge/miyucallback';
                            break;
                        case '1505':
                            $game_data['callback']='http://gundacn5.sudogame.com/charge/miyucallback';
                            break;
                        case '1506':
                            $game_data['callback']='http://gundacn6.sudogame.com/charge/miyucallback';
                            break;
                        case '1507':
                            $game_data['callback']='http://gundacn7.sudogame.com/charge/miyucallback';
                            break;
                        case '1508':
                            $game_data['callback']='http://gundacn8.sudogame.com/charge/miyucallback';
                            break;
                        case '1509':
                            $game_data['callback']='http://gundacn9.sudogame.com/charge/miyucallback';
                            break;
                        case '1510':
                            $game_data['callback']='http://gundacn10.sudogame.com/charge/miyucallback';
                            break;
                        default:
                            $game_data['callback']=$ext['url'].'/charge/miyucallback';
                    }

                }
            }
            if($sdkVersion=='v2.0'){
                $cpParams = array(
                    'game_id'   =>$order['game_id'],
                    'my_order_id'        => $order['my_order_id'],
                    'my_user_id'        => $order['my_user_id'],
                    'role_id'        => $order['role_id'],
                    'server_id'     =>$order['server_id'],
                    'total_price'         => $order['total_price'],//分
                    'game_coin'      => $order['coin'],
                    'cp_order_id'      => $order['cp_order_id'],
                    'pay_time'        => $order['pay_time'],
                    'notify_time'      =>time(),
                    'ext'=>$order['ext']
                );
                ksort($cpParams);
                $string = '';
                foreach($cpParams as $key=>$value){
                    $string .= $key . "=" . $value . "&";
                }
                $string = substr($string, 0, -1);
                $string.=':'.$game['secret'];
                $signature =  md5($string);
                $cpParams['sign'] = $signature;
            }


            if($order['client_id']==107&&$order['game_id']==1176){
                $callback='http://sync.1sdk.cn/cb/ios/miyu/0401CFB5E8E75F5A/sync.html';
            }else{
                $callback=$game['pay_callback'];
            }
            $result = http($callback, $cpParams, 'POST');
        }

        $this->notifyLog(
            $url=$game['pay_callback'],
            json_encode($cpParams),
            trim($result),
            'game_notify',
            $order['game_id'],
            $order['channel_id'],
            $order['my_order_id'],
            trim(strtolower($result))=='success' ? '成功' : '失败',
            ''
        );

        if( trim(strtolower($result)) == 'success' ){
            $save['my_order_id'] = $myOrderId;
            $save['game_result'] = 1;
            $save['game_time'] = time();
            $update = Db::name($table)
                ->where(['my_order_id'=>$myOrderId])
                ->update($save);
            if(!$update){
                $this->layJson(1, '重发失败，请重试');
            }
            $this->layJson(0, '重发成功');
        }else{
            $this->layJson(1, 'CP验证重发失败，请重试');
        }
    }

    private function createSign($params, $key, $val){
        ksort($params);
        $params[$key] = $val;
        $signStr = urldecode(http_build_query($params));
        return md5($signStr);
    }

    private function notifyLog($url,$input,$output,$type,$gameId,$channelId,$myOrderId,$result,$msg)
    {
        if (empty($myOrderId)) {
            return false;
        }
        $data = [
            'url' => $url,
            'input' => $input,
            'output' => $output,
            'time' => time(),
            'type' => $type,
            'game_id' => $gameId,
            'channel_id' => $channelId,
            'my_order_id' => $myOrderId,
            'result' => $result,
            'msg' => $msg
        ];

        try {
            $table = get_order_table($myOrderId);
            $rs1 = Db::name($table)->where(['my_order_id'=>$myOrderId])->update(['notifyed'=>1]);
            $rs2 = Db::name(get_order_log_table($myOrderId))->insert($data);
            if ($rs1 && $rs2) {
                return true;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return false;
        }
    }

}